import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:heven/widget/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:device_info/device_info.dart';
import 'package:package_info/package_info.dart';
import 'package:heven/model/user_model.dart';
import 'package:flutter_keychain/flutter_keychain.dart';

class Common {
  static mergeParams(params) {
    DateTime now = DateTime.now();
    int timestampInSeconds = (now.millisecondsSinceEpoch / 1000).round();
    var random = Random();
    int randomInt = random.nextInt(1000001);
    Map<String, dynamic> merged = {
      "req_nonce": randomInt.toString(), // 随机字符串
      "req_timestamp": timestampInSeconds, // 请求时间戳
      ...params
    };

    return merged;
  }

  static getPackageInfo() async {
    final packageInfo = await PackageInfo.fromPlatform();
    print(packageInfo);
    Common.saveStorageValue('packageName', packageInfo.packageName);
    Common.saveStorageValue('appName', packageInfo.appName);
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    bool isIos = Platform.isIOS;
    String platform = isIos ? 'iOS' : 'Android';
    Common.saveStorageValue('platform', platform);
    String systemVersion;
    String? uuid;
    if (isIos) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      systemVersion = iosInfo.systemVersion;

      // print("uuid:${iosInfo.identifierForVendor}");
      var oldUuid = await FlutterKeychain.get(key: "uuid");
      if (oldUuid == null) {
        uuid = iosInfo.identifierForVendor; // iOS 上的 UUID
        await FlutterKeychain.put(key: "uuid", value: uuid);
        Common.saveStorageValue('udid', uuid.toString());
      } else {
        Common.saveStorageValue('uuid', oldUuid);
      }
      Common.saveStorageValue('version', systemVersion);
    } else {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      print(androidInfo);
      print(androidInfo.androidId);
      systemVersion = androidInfo.version.release;
      Common.saveStorageValue('udid', androidInfo.androidId.toString());
      Common.saveStorageValue('uuid', androidInfo.androidId.toString());
      Common.saveStorageValue('version', systemVersion);
    }
    String userAgent =
        "aimusic/${packageInfo.packageName}/1.0.2/10010/zh-CN (${platform} ${systemVersion})";
    Common.saveStorageValue('userAgent', userAgent);
  }

  static Future<void> saveStorageValue(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);
  }

  static Future<String?> getStorageValue(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  static Future<void> removeStorageValue(String key) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);
  }

  static generateSign(data) {
    // 将数据对象转换为 JSON 字符串
    final jsonString = jsonEncode(data);
    // 使用 SHA-1 计算哈希值
    final bytes = utf8.encode(jsonString);
    final digest = sha1.convert(bytes);
    return digest.toString();
  }

  static int getMillisecond() {
    DateTime now = DateTime.now();

    return now.millisecondsSinceEpoch;
  }

  static String formatDuration(int milliseconds) {
    int hours = (milliseconds ~/ 3600000); // 每小时的毫秒数
    int minutes = (milliseconds ~/ 60000) % 60; // 每分钟的毫秒数
    int seconds = (milliseconds ~/ 1000) % 60; // 每秒的毫秒数
    int millis = milliseconds % 1000; // 剩余的毫秒

    // 补齐两位数
    //
    String hourStr = hours.toString().padLeft(2, '0');
    String minuteStr = minutes.toString().padLeft(2, '0');
    String secondStr = seconds.toString().padLeft(2, '0');
    String millisStr = millis.toString().padLeft(2, '0');
    return '$hourStr:$minuteStr: $secondStr';
  }

  static loadingDialog(context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return LoadingWidget();
      },
    );
  }

  static Future<bool> checkNetworkStatus() async {
    var connectivityResult = await Connectivity().checkConnectivity();
    print(' connectivityResult: $connectivityResult');
    return connectivityResult[0] != ConnectivityResult.none;
  }

  static listenToConnectivity(callback) {
    Connectivity().onConnectivityChanged.listen((result) {
      callback(result == ConnectivityResult.none);
      // if () {
      //   print("无网络连接");
      // } else {
      //   print("有网络连接");
      // }
    });
  }

  static Future<void> saveUser(loginResponse) async {
    UserModel userModel = UserModel.fromJson(loginResponse);

    // // 存储 Token 和 Uid
    await Common.saveStorageValue('token', userModel.token);
    await Common.saveStorageValue('uid', userModel.uid ?? '');
  }
}
